﻿using AutoMapper;
using Domain.Factory_Modeling;
using Infratructure.Interface;
using MD5Hash;
using MediatR;
using ReturnValue;
using Yitter.IdGenerator;

namespace MES.Server.API.Application.Command.Factory_Modeling
{
    public class AddWorkShopHander : IRequestHandler<AddWorkShopCommand, ApiResult<int>>
    {
        private readonly IRepository<WorkShopModel> workflowRepo;
        private readonly IMapper mapper;
        public AddWorkShopHander(IRepository<WorkShopModel> workflowRepo, IMapper mapper)
        {
           this.workflowRepo = workflowRepo;
           this.mapper = mapper;
        }
        /// <summary>
        /// 添加车间
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(AddWorkShopCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();
            //车间编码不能重复
            var exists = workflowRepo.GetAll().Where(a => a.WorkShopCode == request.WorkShopCode).FirstOrDefault();
            if(exists!=null)
            {
                result.Code = StatusCode.Fail;
                result.Message = "该车间编码已存在，请重新输入！";
                return await  Task.FromResult(result);
            }
            var model = mapper.Map<WorkShopModel>(request);
            model.Id = YitIdHelper.NextId();
            model.CreateTime = DateTime.Now;
            model.IsDel = false;
            if (model != null)
            {
                await workflowRepo.AddAsync(model);
                result.Code = StatusCode.Success;
                result.Message = "添加成功！";
                return await Task.FromResult(result);
            }
            else
            {
                result.Code = StatusCode.Fail;
                result.Message = "添加失败！";
                return await Task.FromResult(result);
            }
        }
    }
}
